package com.zjj.algorithm.learning.dmsxl.tree;

/**
 * 翻转二叉树
 *
 * @author zjj_admin
 * @date 2022/12/22 11:13
 */
public class Tree_06_InvertBinaryTree {


    public static void main(String[] args) {

        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);

        node1.left = node2;
        node1.right = node3;

        invertTree(node1);
        System.out.println("node3 = " + node3);

    }


    /**
     * 使用递归的方法进行反转
     * 采用前序或者后续遍历的方式对每一个节点的左右孩子节点交换位置
     * <p>
     * 时间
     * 0 ms
     * 击败
     * 100%
     * 内存
     * 39.2 MB
     * 击败
     * 36.5%
     *
     * @param root
     * @return
     */
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        swapChild(root);
        invertTree(root.left);
        invertTree(root.right);
        return root;
    }

    private static void swapChild(TreeNode root) {
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
    }


}
